package crmsystem.config;

import crmsystem.utils.MyCodeEnum;
import crmsystem.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理校验异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "crmsystem.controller")
public class MyExceptionAdvice {
    @ExceptionHandler(value = Exception.class)
    public R handleValidException(MethodArgumentNotValidException exception /*Exception e*/){
        Map<String,String> map=new HashMap<>();
        BindingResult bindingResult = exception.getBindingResult();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            String message = fieldError.getDefaultMessage();//检验错误消息
            String field = fieldError.getField();//校验的字段
            map.put(field,message);
        });
        log.error("数据校验出现问题{},异常类型{}",/*e.getMessage(),e.getClass()*/exception.getMessage(),exception.getClass());
        return R.error(MyCodeEnum.VALID_EXCEPTION.getCode(),MyCodeEnum.VALID_EXCEPTION.getMsg()).put("data",map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R localexception(Throwable throwable){
        log.error("未知异常{},异常类型{}",throwable.getMessage(),throwable.getClass());
        return R.error(MyCodeEnum.UNKNOW_EXEPTION.getCode(),MyCodeEnum.UNKNOW_EXEPTION.getMsg());
    }
}
